use strict;
use warnings;
use Test::More;
use File::Spec;
use Circle::Miner;
use POSIX;
use Carp;

# 测试模块加载
BEGIN { use_ok('Circle::Miner') }

# 测试构造函数
my $miner = new_ok('Circle::Miner');

# 测试 make_ranges 方法
subtest 'make_ranges tests' => sub {
    my $ranges;
    
    # 测试单线程情况
    $ranges = $miner->make_ranges(1);
    is(scalar @$ranges, 1, 'Single thread should create one range');
    is($ranges->[0][0], 0, 'First range should start at 0');
    is($ranges->[0][1], 100, 'First range should end at 100');

    # 测试多线程情况
    $ranges = $miner->make_ranges(4);
    is(scalar @$ranges, 4, 'Four threads should create four ranges');
    is($ranges->[0][0], 0, 'First range should start at 0');
    
    # 验证范围的连续性
    for my $i (0..2) {
        is($ranges->[$i][1], $ranges->[$i+1][0], "Range $i should connect with range ".($i+1));
    }
    is($ranges->[3][1], 100, 'Last range should end at 100');
};

# 测试 get_os_arch 方法
subtest 'get_os_arch tests' => sub {
    my ($os, $arch) = Circle::Miner::get_os_arch();
    ok(defined $os, 'OS should be defined');
    ok(defined $arch, 'Architecture should be defined');
    like($os, qr/^[a-zA-Z0-9_]+$/, 'OS should be a valid string');
    like($arch, qr/^[a-zA-Z0-9_]+$/, 'Architecture should be a valid string');
};

# 测试 fetch_my_block 方法的参数验证
subtest 'fetch_my_block parameter validation' => sub {
    eval {
        $miner->fetch_my_block();
    };
    like($@, qr/address must be provided!/, 'fetch_my_block should fail without address parameter');
};

# 测试 mine_block 方法的参数验证
subtest 'mine_block parameter validation' => sub {
    eval {
        $miner->mine_block();
    };
    carp "error: $@";
    like($@, qr/header_hex is required/, 'mine_block should fail without header_hex parameter');
    
    eval {
        $miner->mine_block('invalid_hex');
    };
    carp "error: $@";
    like($@, qr/header_hex is invalid/, 'mine_block should fail with invalid header_hex');
};

# 测试 post_my_block 方法的参数验证
subtest 'post_my_block parameter validation' => sub {
    eval {
        $miner->post_my_block();
    };
    like($@, qr/address header_hex and ip_port must be non-empty/, 'post_my_block should fail without parameters');
    
    eval {
        $miner->post_my_block('address', 'header-hex', '123.2.34.5:80');
    };
    like($@, qr/address is invalid/, 'post_my_block should fail without all required parameters');
};

done_testing(); 
